//
//  HSFSwitchOnlineHandle.m
//  UILbrary
//
//  Created by Apple on 2023/2/27.
//  Copyright © 2023 mac. All rights reserved.
//

#import "HSFSwitchOnlineHandle.h"
#import "UIButton+Utils.h"

@interface HSFSwitchOnlinData : NSObject

@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *icon;
@property (nonatomic, assign) HSFOnlineStatus onlineStatu;

@end

@implementation HSFSwitchOnlinData
@end

@interface HSFOnlineCell : UITableViewCell

@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UIImageView *icon;
@property (nonatomic, strong) UIView *bgview;
@property (nonatomic, strong) UIStackView *stackView;


@end

@implementation HSFOnlineCell


//MARK: - system
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self){
        [self p_configSubviews];
        [self p_clearStyle];
//        [self test];
    }
    return self;
}

//MARK: - test

- (void)test
{
    self.label.text = @"上线中";
    self.icon.image = [UIImage imageNamed:@"hsf_busy_icon"];
}

//MARK: - public

- (void)configData:(HSFSwitchOnlinData *)data
{
    self.label.text = data.title;
    self.icon.image = [UIImage imageNamed:data.icon];
}

//MARK: - privat

- (void)p_configSubviews
{
    [self.contentView addSubview:self.bgview];
    [self.bgview addSubview:self.stackView];


    [self.bgview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.contentView);
        make.height.mas_equalTo(50);
    }];
    
    [self.stackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.bgview);
    }];
    
    [self.icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(16);
        make.width.mas_equalTo(16);
    }];
}

- (void)p_clearStyle
{
    self.backgroundColor = [UIColor clearColor];
    self.bgview.backgroundColor = [UIColor clearColor];
    self.stackView.backgroundColor = [UIColor clearColor];
}

//MARK: - get

- (UIView *)bgview
{
    if(!_bgview){
        _bgview = [UIView new];
    }
    return _bgview;
}

- (UILabel *)label
{
    if(!_label){
        _label = [UILabel new];
        _label.font = [UIFont systemFontOfSize:16.0];
        _label.textAlignment = NSTextAlignmentCenter;
        _label.textColor = [UIColor whiteColor];
    }
    return _label;
}

- (UIImageView *)icon
{
    if(!_icon){
        _icon = [UIImageView new];
    }
    return _icon;
}

- (UIStackView *)stackView
{
    if(!_stackView){
        
        UIView *view_1 = [UIView new];
        [view_1 setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
        UIView *view_2 = [UIView new];
        [view_2 setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
        
        
        _stackView = [UIStackView new];
        
        [_stackView addArrangedSubview:view_1];
        [_stackView addArrangedSubview:self.icon];
        [_stackView addArrangedSubview:self.label];
        [_stackView addArrangedSubview:view_2];
        _stackView.axis = UILayoutConstraintAxisHorizontal;
        _stackView.distribution = UIStackViewDistributionFill;
        _stackView.alignment = UIStackViewAlignmentCenter;
        _stackView.spacing = 10;
        
        [view_1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(view_2);
        }];
    }
    return _stackView;
}

@end


@interface HSFSwitchOnlinePopView : UIView<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UIView *maskView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) CGPoint anchorPoint;
@property (nonatomic, strong) NSArray <HSFSwitchOnlinData *>*dataList;

@property (nonatomic, copy) void(^selectBlock)(HSFSwitchOnlinePopView *view, NSInteger idx);

@end

@implementation HSFSwitchOnlinePopView


//MARK: - system

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self){
//        [self test];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.tableView.contentSize.height);
    }];
    
}

- (void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    
    [self p_drawTriangle];
}


//MARK: - public

+ (void)showAnchorPoint:(CGPoint)point
               dataList:(NSArray <HSFSwitchOnlinData *>*)dataList
            selectBlock:(void(^)(HSFSwitchOnlinePopView *view, NSInteger idx))selectBlock
{
    if(!selectBlock) return;

    NSLog(@"show");
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    HSFSwitchOnlinePopView *view = [HSFSwitchOnlinePopView new];
    [window addSubview:view];
    
    view.dataList = dataList;
    view.selectBlock = selectBlock;
    view.anchorPoint = point;
    [view configSubviews];
    
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(window);
    }];
}

- (void)dismiss
{
    NSLog(@"dismiss");
    [self removeFromSuperview];
}


- (void)configSubviews
{
    NSLog(@"p_configSubviews");
    [self addSubview:self.bgView];
    [self addSubview:self.tableView];
    
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.mas_top).offset(self.anchorPoint.y);//self.anchorPoint.y
        make.left.mas_equalTo(self.mas_left).offset(self.anchorPoint.x);//self.anchorPoint.x - 100
        make.width.mas_equalTo(110);
        make.height.mas_equalTo(1000);
    }];
}

//MARK: - test

- (void)test
{
//    self.tableView.backgroundColor = [UIColor redColor];
//    self.bgView.backgroundColor = [UIColor yellowColor];
}


//MARK: - private

- (void)p_initConfig
{
    NSLog(@"p_initConfig");
}

- (void)p_drawTriangle
{
    CGPoint orign = self.tableView.frame.origin;

    //画三角箭头
    CGFloat width = 12.0;
    CGFloat beginX = orign.x + 20;
    CGFloat endX = beginX + width;
    CGFloat centerX = (beginX + endX) / 2.0;
    CGFloat topY = orign.y - 6;
    CGFloat bottomY = orign.y;
    
    
    CAShapeLayer *triangleLayer = [CAShapeLayer layer];
    triangleLayer.strokeColor = self.tableView.backgroundColor.CGColor;
    triangleLayer.fillColor = self.tableView.backgroundColor.CGColor;

    UIBezierPath *trianglePath = [UIBezierPath bezierPath];
    [trianglePath moveToPoint:CGPointMake(beginX, bottomY)];
    [trianglePath addLineToPoint:CGPointMake(centerX, topY)];
    [trianglePath addLineToPoint:CGPointMake(endX, bottomY)];
    [trianglePath closePath];

    triangleLayer.path = trianglePath.CGPath;
    [self.layer addSublayer:triangleLayer];

}

//MARK: - Action

- (void)tapAction
{
    NSLog(@"tapAction");
    [self dismiss];
}

//MARK: - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HSFOnlineCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HSFOnlineCell"];
    if(!cell){
        cell = [HSFOnlineCell new];
    }
    [cell configData:self.dataList[indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"didSelectRowAtIndexPath");
    [self dismiss];
    
    if(!self.selectBlock) return;
    self.selectBlock(self, indexPath.row);
}

//MARK: - get

- (UIView *)bgView
{
    if(!_bgView){
        _bgView = [UIView new];
        _bgView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.2];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
        [_bgView addGestureRecognizer:tap];
    }
    return _bgView;
}

- (UITableView *)tableView
{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        [_tableView registerClass:[HSFOnlineCell class] forCellReuseIdentifier:@"HSFOnlineCell"];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 100;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.8];
        _tableView.layer.cornerRadius = 6.0;
    }
    return _tableView;
}

@end


@interface HSFSwitchOnlineHandle(DataSource)

+ (NSArray <HSFSwitchOnlinData *>*)dataSource;
+ (NSDictionary *)dataConfigDic;

@end

@interface HSFSwitchOnlineView : UIView
/// online button 上/下 线 按钮
@property (nonatomic, strong) UIButton *switchOnlineButton;
@property (nonatomic, strong) NSArray <HSFSwitchOnlinData *>*dataList;

@end

@implementation HSFSwitchOnlineView

//MARK: - system

- (instancetype)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame];
  if(self){
      [self p_configSubviews];
      [self test];
  }
  return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self.switchOnlineButton layoutButtonWitdEdgeInsetsStyle:HSFButtonEdgeInsetsStyleRight imageTitleSpace:0];
}

//MARK: - test

- (void)test
{
    self.switchOnlineButton.backgroundColor = [UIColor redColor];
}

- (void)test_anchorPoint
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *redVIew = [UIView new];
    redVIew.backgroundColor = [UIColor redColor];
    [window addSubview:redVIew];
    
    CGPoint point = [self p_anchorPoint];
    redVIew.frame = CGRectMake(point.x, point.y, 100, 100);
}

//MARK: - public

- (void)changeOnlineStatu:(HSFOnlineStatus)statu
{
    NSDictionary *dic = [HSFSwitchOnlineHandle dataConfigDic];
    HSFSwitchOnlinData *data = dic[@(statu)];
    [self.switchOnlineButton setTitle:data.title forState:UIControlStateNormal];
}

//MARK: - private

- (void)p_configSubviews
{
  [self addSubview:self.switchOnlineButton];
  [self.switchOnlineButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.mas_equalTo(self).insets(UIEdgeInsetsMake(10, 10, 10, 10));
  }];
}

- (CGPoint)p_anchorPoint
{
    [self layoutIfNeeded];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    CGRect rect = self.bounds;
    rect = [self convertRect:rect toView:window];
    CGFloat y = CGRectGetMaxY(rect);
    CGFloat x = CGRectGetMinX(rect);//CGRectGetMaxX(rect) - rect.size.width / 2.0 ;
    return CGPointMake(x, y);
}

//MARK: - action

- (void)switchOnlineButtonAction
{
    NSLog(@"switchOnlineButtonAction click");
    [HSFSwitchOnlinePopView showAnchorPoint:[self p_anchorPoint]
                                dataList:self.dataList
                                selectBlock:^(HSFSwitchOnlinePopView *view, NSInteger idx) {
        HSFSwitchOnlinData *data = self.dataList[idx];
        [self changeOnlineStatu:data.onlineStatu];
    }];
}

- (void)changeTitle:(NSString *)title
{
    NSLog(@"按钮文字改变");
}

////MARK: - get

- (UIButton *)switchOnlineButton
{
  if(!_switchOnlineButton){
      UIButton *button = [UIButton new];
      [button addTarget:self action:@selector(switchOnlineButtonAction) forControlEvents:UIControlEventTouchUpInside];
      [button setTitle:@"下线中" forState:UIControlStateNormal];
      [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
      [button setImage:[UIImage imageNamed:@"online_icon"] forState:UIControlStateNormal];
      button.titleLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightMedium];
      _switchOnlineButton = button;
  }
  return _switchOnlineButton;
}

@end



@interface HSFSwitchOnlineHandle()

@property (nonatomic, strong) HSFSwitchOnlineView *p_view;

@end



@implementation HSFSwitchOnlineHandle


//MARK: - public

- (void)changeOnlineStatu:(HSFOnlineStatus)statu
{
    [self.p_view changeOnlineStatu:statu];
}

//MARK: - get

- (HSFSwitchOnlineView *)p_view
{
  if(!_p_view){
      _p_view = [HSFSwitchOnlineView new];
      _p_view.dataList = [HSFSwitchOnlineHandle dataSource];
  }
  return _p_view;
}

- (UIView *)view
{
  return self.p_view;
}


@end



@implementation HSFSwitchOnlineHandle(DataSource)

+ (NSArray <HSFSwitchOnlinData *>*)dataSource
{
    NSDictionary *dic = [self dataConfigDic];
    return @[dic[@(HSFOnlineStatus_online)],
             dic[@(HSFOnlineStatus_offline)],
             dic[@(HSFOnlineStatus_busy)]];
}

+ (NSDictionary *)dataConfigDic
{
    NSMutableDictionary *dic = [@{} mutableCopy];
    
    HSFSwitchOnlinData *online = [HSFSwitchOnlinData new];
    online.title = @"上线中";
    online.icon = @"hsf_online_icon";
    online.onlineStatu = HSFOnlineStatus_online;
    
    HSFSwitchOnlinData *offline = [HSFSwitchOnlinData new];
    offline.title = @"下线中";
    offline.icon = @"hsf_offline_icon";
    offline.onlineStatu = HSFOnlineStatus_offline;
    
    HSFSwitchOnlinData *busyline = [HSFSwitchOnlinData new];
    busyline.title = @"忙碌中";
    busyline.icon = @"hsf_busy_icon";
    busyline.onlineStatu = HSFOnlineStatus_busy;
    
    dic[@(HSFOnlineStatus_online)] = online;
    dic[@(HSFOnlineStatus_offline)] = offline;
    dic[@(HSFOnlineStatus_busy)] = busyline;
    
    return [dic copy];
}


@end
